<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" :placeholder="$t('请输入订阅名称')"/>
      <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value"/>
      <el-select v-model="listQuery.useRange" clearable style="width: 200px" class="filter-item" :placeholder="$t('请选择使用范围')">
        <el-option v-for="type in useRangeOptions" :key="type.value" :label="type.label" :value="type.value"/>
      </el-select>
      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" :placeholder="$t('请选择订阅状态')">
        <el-option v-for="type in statusOptions" :key="type.value" :label="type.label" :value="type.value"/>
      </el-select>
      <el-button v-permission="['GET /admin/p/lumiere_subscribe_index']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{$t('Search')}}</el-button>
      <el-button v-permission="['GET /admin/p/lumiere_subscribe_add']" class="filter-item" type="warning" plain1 icon="el-icon-circle-plus" @click="handleCreate">{{$t('Add')}}</el-button>
      <!--      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{$t('Find')}}</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit highlight-current-row>
      <el-table-column type="index" :index="getIndex" width="50"></el-table-column>

      <el-table-column align="center" :label="$t('订阅_ID')" prop="id" sortable/>

      <el-table-column align="center" :label="$t('订阅名称')" prop="name"/>

      <el-table-column align="center" property="picture" :label="$t('Picture')">
        <template slot-scope="scope">
          <el-image preview-src-list style="border-radius:15%;width:60px" :src="scope.row.picture"  lazy>
            <div slot="error" class="image-slot">
              <i style="font-size: 30px" class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('可订阅方式')" prop="methods">
        <template slot-scope="scope">
          <el-row v-for="rule in scope.row.rules">
            {{filterRuleTypes(rule.ruleType)}}
          </el-row>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('使用范围')" prop="useRange">
        <template slot-scope="scope">
          <el-tag>
            {{filterUseRange(scope.row.useRange)}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" :label="$t('购买金额')" prop="price">
        <template slot-scope="scope">
          <el-row v-for="rule in scope.row.rules">
            ${{rule.price}} or {{rule.point}}pts
          </el-row>
        </template>
      </el-table-column>
      <!-- <el-table-column width="100" align="center" :label="$t('购买金额')" prop="price">
        <template slot-scope="scope">
          <el-row v-for="rule in scope.row.rules">
            <span style="display: block;">${{rule.price}}</span>
            <span style="display: block;">or</span>
            <span style="display: block;">{{rule.point}}pts</span>
          </el-row>
        </template>
      </el-table-column> -->

      <el-table-column width="150" align="center" :label="$t('续约金额')" prop="price">
        <template slot-scope="scope">
          <el-row v-for="rule in scope.row.rules">
            ${{rule.nextSubPrice}} or {{rule.nextSubPoint}}pts
          </el-row>
        </template>
      </el-table-column>

      <!-- <el-table-column width="100" align="center" :label="$t('续约金额')" prop="price">
        <template slot-scope="scope">
          <el-row v-for="rule in scope.row.rules">
            <span style="display: block;">${{rule.nextSubPrice}}</span>
            <span style="display: block;">or</span>
            <span style="display: block;"> {{rule.nextSubPoint}}pts</span>
          </el-row>
        </template>
      </el-table-column> -->

      <el-table-column width="120" align="center" :label="$t('配送时间范围')" prop="timeRanges">
        <template slot-scope="scope">
          <el-tag type="info" effect="plain1">
            {{filterTimeRanges(scope.row.timeRanges)}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" :label="$t('是否支持自动续订')" prop="autoSub">
        <template slot-scope="scope">
          <el-tag type="info" effect="plain1">
            {{filterAutoSub(scope.row.autoSub)}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column width="120" align="center" :label="$t('添加时间')" prop="addTime">

      </el-table-column>

      <el-table-column align="center" :label="$t('状态')" prop="status">
        <template slot-scope="scope">
          <el-tag>
            {{filterStatus(scope.row.status)}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column fixed="right" align="center" :label="$t('Operate')" width="300" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
<!--          <el-button v-permission="['GET /admin/p/elec_coupon_detail']" type="primary" plain1 size="mini" @click="handleDetail(scope.row)">{{$t('Details')}}</el-button>-->
          <el-button v-permission="['GET /admin/p/lumiere_subscribe_edit']" icon="el-icon-view"  type="info" plain1 size="mini" @click="handleUpdate(scope.row)">{{ $t(scope.row.status == 1 ? '查看' : '编辑')}}</el-button>
          <el-button v-permission="['GET /admin/p/lumiere_subscribe_status']"  type="info" plain1 size="mini" @click="handleStatus(scope.row)">{{formateStatus(scope.row.status)}}</el-button>
          <el-button v-show="scope.row.status != 1" v-permission="['GET /admin/p/lumiere_subscribe_delete']"icon="el-icon-delete" plain1 type="danger" size="mini" @click="handleDelete(scope.row)">{{$t('Delete')}}</el-button>
<!--          <el-button plain1 size="mini" @click="handleStatistic(scope.row)">{{$t('统计')}}</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { listLumiereSubscribe } from '@/api/lumiereSubscribe'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { uploadPath } from '../../api/storage'
import { getToken } from '../../utils/auth'
import { changeSubscribeStatus, deleteSubscribe } from '../../api/lumiereSubscribe'


export default {
  name: 'subscribeList',
  components: { Pagination },
  filters: {},
  data() {
    const defaultTypeOptions = [
      {
        label: this.$t('订阅设置'),
        value: 1
      }

    ]

    const defaultStatusOptions = [
      {
        label: this.$t('停用'),
        value: 0
      },
      {
        label: this.$t('启用'),
        value: 1
      },
      {
        label: this.$t('新增'),
        value: 2
      }
    ]

    const defaultUseRangeOptions = [
      {
        label: this.$t('通用'),
        value: 1
      },
      {
        label: this.$t('门店使用'),
        value: 2
      },
      {
        label: this.$t('网店使用'),
        value: 3
      }
    ]

    const validateDiscount = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 1 && !value) {
        return callback(new Error(this.$t('满减金额不能为空')));
      }

      callback();
    }

    const validateDiscountRate = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 2 && !value) {
        return callback(new Error(this.$t('百分比不能为空')));
      }

      callback();
    }

    const validateDays = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 0 && !value) {
        return callback(new Error(this.$t('相对天数不能为空')));
      }

      callback();
    }

    const validateStartTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('开始时间不能为空')));
      }

      callback();
    }

    const validateEndTime = (rule, value, callback) => {
      let timeType = this.dataForm.timeType
      if (timeType == 1 && !value) {
        return callback(new Error(this.$t('结束时间不能为空')));
      }

      callback();
    }

    const validateGoodsValue = (rule, value, callback) => {
      let goodsType = this.dataForm.goodsType
      if (goodsType == 1 && value.length == 0) {
        return callback(new Error(this.$t('商品分类不能为空')));
      }
      callback();
    }

    const validateRegions = (rule, value, callback) => {
      let regions = this.dataForm.regions;
      if(regions && regions.length == 0){
        return callback(new Error(this.$t('区域不能为空')));
      }
    }

    return {
      uploadPath,
      isLevelMember: false,
      isMoneyMember: false,
      defaultTypeOptions,
      defaultStatusOptions,
      typeOptions: Object.assign({}, defaultTypeOptions),
      statusOptions: Object.assign({}, defaultStatusOptions),
      useRangeOptions: Object.assign({}, defaultUseRangeOptions),
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        status: undefined,
        useRange: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      goodsList: [],
      listGoodsQuery: {
        page: 1,
        limit: 10000,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: undefined,
        picture: undefined,
        distributionStartTime: '',
        distributionEndTime: '',
        autoSub: 0,
        transportType: 1,
        orderRule: 1,
        useRange: 1,
        shopIds: [],
        areaLimit: 0,
        weekRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        monthRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        yearRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: this.$t('Edit'),
        create: this.$t('Create')
      },
      rules: {
        name: [
          { required: true, message: this.$t('Coupon_title_cannot_be_empty'), trigger: 'blur' }
        ],
        discount: [
          { validator: validateDiscount, trigger: 'blur' }
        ],
        discountRate: [
          { validator: validateDiscountRate, trigger: 'blur' }
        ],
        min: [
          { required: true, trigger: 'blur' }
        ],
        limit: [
          { required: true, trigger: 'blur' }
        ],
        total: [
          { required: true, trigger: 'blur' }
        ],
        useLimit: [
          { required: true, trigger: 'change', message: this.$t('用户限制类型不能为空') }
        ],
        useLimitNum: [
          { required: true, trigger: 'blur' }
        ],
        timeType: [
          { required: true, trigger: 'blur' }
        ],
        days: [
          { validator: validateDays, trigger: 'blur' }
        ],
        startTime: [
          { validator: validateStartTime, trigger: 'blur' }
        ],
        endTime: [
          { validator: validateEndTime, trigger: 'blur' }
        ],
        goodsValue: [
          { validator: validateGoodsValue, trigger: 'blur' }
        ],
        regions: [
          {validator: validateRegions, trigger: 'blur'}
        ]
      },
      downloadLoading: false,

      props: { multiple: true, value: 'id', label: 'name',emitPath:false},
      regionProps: {multiple: true, value: 'id', label: 'nameEn',emitPath:false},
      subscribeSpecifications: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    filterUseRange(useRange){
      if(useRange == 1){
        return this.$t("通用")
      }else if(useRange == 2){
        return this.$t("门店使用")
      }else{
        return this.$t("网店使用")
      }

    },
    filterTimeRanges(timeRanges){
      if(timeRanges == "[]"){
        return this.$t("无配置");
      }else{
        return timeRanges;
      }
    },
    filterAutoSub(autoSub){
      if(autoSub == 1){
        return this.$t("支持")
      }else{
        return this.$t("不支持")
      }
    },
    filterStatus(status){
      if(status == 2){
        return this.$t("新增")
      }else if(status == 1){
        return this.$t("启用")
      }else{
        return this.$t("停用")
      }
    },
    filterRuleTypes(rule){
      let rules = "";
          if(rule == 1){
            rules += this.$t('周')
          }else if(rule == 2){
            rules += this.$t('月')
          }else {
            rules += this.$t('年')
          }
      return rules
    },
    getList() {
      this.listLoading = true
      listLumiereSubscribe(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

      this.$router.push({ name: 'subscribeAdd', query: { dataForm : this.dataForm, dialogStatus : this.dialogStatus} })
    },

   handleUpdate(row) {
     this.resetForm()
     this.dialogStatus = 'update'
     this.$nextTick(() => {
       this.$refs['dataForm'].clearValidate()
     })
     this.$router.push({ name: 'subscribeAdd', query: { id : row.id, dialogStatus : this.dialogStatus} })
   },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        picture: undefined,
        distributionStartTime: '',
        distributionEndTime: '',
        autoSub: 0,
        transportType: 1,
        orderRule: 1,
        useRange: 1,
        shopIds: [],
        areaLimit: 0,
        weekRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        monthRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 1,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        yearRule: {
          id: undefined,
          type: 1,
          dayTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        subscribeSpecifications: [],
      }
    },
    formateStatus(status){
      if (status === 0) {
        return this.$t('启用')
      } else if (status === 1) {
        return this.$t('停用')
      } else if (status === 2) {
        return this.$t('启用')
      } else {
        return this.$t('Merchandise_removed')
      }
    },
    handleDelete(row) {
      this.$confirm(this.$t('Confirm_Delete?'), this.$t('Hint'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.doDelete(row)
      });
    },
    doDelete(row) {
      deleteSubscribe(row)
        .then(response => {
          this.$notify.success({
            title: this.$t('Success!'),
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
    },
    handleStatus(row){
      this.$confirm(this.$t('是否') + this.$t('改变订阅设置状态') + "?", this.$t('提示'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.doIgnore(row)
      });
    },
    doIgnore(row){
      let data = {
        id: row.id
      }
      changeSubscribeStatus(data).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('Success!')
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
  },

  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  }

}
</script>
